package com.example.floatingclockdemo

import android.animation.ValueAnimator
import android.annotation.SuppressLint
import android.app.Service
import android.content.Intent
import android.content.res.Resources
import android.graphics.Color
import android.graphics.PixelFormat
import android.graphics.Typeface
import android.graphics.drawable.GradientDrawable
import android.os.Handler
import android.os.IBinder
import android.os.Looper
import android.util.DisplayMetrics
import android.view.Gravity
import android.view.MotionEvent
import android.view.View
import android.view.ViewGroup
import android.view.WindowManager
import android.widget.LinearLayout
import android.widget.TextView
import androidx.appcompat.widget.AppCompatButton
import androidx.core.graphics.toColorInt
import java.text.SimpleDateFormat
import java.util.Date
import java.util.Locale
import kotlin.math.absoluteValue

class ClockService : Service() {
    private lateinit var wm: WindowManager
    private lateinit var layoutParams: WindowManager.LayoutParams
    private lateinit var displayMetrics: DisplayMetrics

    private val handler = Handler(Looper.getMainLooper())
    private val formatter = SimpleDateFormat("HH:mm:ss.S", Locale.getDefault())
    private val prefs by lazy { getSharedPreferences("clock_prefs", MODE_PRIVATE) }

    private lateinit var rootLayout: LinearLayout
    private lateinit var collapsedText: TextView
    private lateinit var hideButton: AppCompatButton
    private var isExpanded = false

    private val autoCollapseHandler = Handler(Looper.getMainLooper())
    private val autoCollapseRunnable = Runnable {
        toggleView(false)
    }

    private val updateRunnable = object : Runnable {
        override fun run() {
            val now = formatter.format(Date())
            collapsedText.text = now
            handler.postDelayed(this, 100)
        }
    }

    @SuppressLint("SetTextI18n")
    override fun onCreate() {
        super.onCreate()

        wm = getSystemService(WINDOW_SERVICE) as WindowManager
        displayMetrics = DisplayMetrics().also {
            wm.defaultDisplay.getMetrics(it)
        }

        val savedX = prefs.getInt("x", 200)
        val savedY = prefs.getInt("y", 400)

        layoutParams = WindowManager.LayoutParams(
            WindowManager.LayoutParams.WRAP_CONTENT,
            WindowManager.LayoutParams.WRAP_CONTENT,
            WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY,
            WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE or
                    WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS,
            PixelFormat.TRANSLUCENT
        ).apply {
            gravity = Gravity.TOP or Gravity.START
            x = savedX
            y = savedY
        }

        // 根容器
        rootLayout = LinearLayout(this).apply {
            orientation = LinearLayout.VERTICAL
            background = GradientDrawable().apply {
                // 设置圆角，单位是像素
                cornerRadius = 10f
                setColor("#99000000".toColorInt()) // 半透明背景
            }
            setPadding(60, 20, 60, 20)
            layoutParams = ViewGroup.LayoutParams(
                ViewGroup.LayoutParams.WRAP_CONTENT,
                ViewGroup.LayoutParams.WRAP_CONTENT
            )
        }

        // 显示时间的 TextView
        collapsedText = TextView(this).apply {
            setTextColor(Color.GREEN)
            textSize = 18f
            // 设置等宽加粗字体
            setTypeface(Typeface.MONOSPACE, Typeface.BOLD)
            // 初始化最大宽度
            // 初始化为最大宽度
            text = "00:00:00.0"
        }

        // 隐藏按钮
        hideButton = AppCompatButton(this).apply {
            text = "关闭"
            textSize = 15f
            setPadding(40, 12, 40, 12)
            gravity = Gravity.CENTER
            background = GradientDrawable().apply {
                cornerRadius = 10f
                setColor("#FFFFFF".toColorInt())
            }
            layoutParams = LinearLayout.LayoutParams(
                LinearLayout.LayoutParams.WRAP_CONTENT,
                LinearLayout.LayoutParams.WRAP_CONTENT
            ).apply {
                setMargins(0, 20, 0, 15)
                gravity = Gravity.CENTER_HORIZONTAL
            }
            visibility = View.GONE
            setOnClickListener {
                stopSelf()

                // 通知 MainActivity 更新按钮状态
                val intent = Intent(BROADCAST_CLOCK_SERVICE_STOP).apply {
                    // 确保广播只发给自己 app
                    `package` = context.packageName
                }
                sendBroadcast(intent)
            }
        }

        rootLayout.addView(collapsedText)
        rootLayout.addView(hideButton)

        wm.addView(rootLayout, layoutParams)

        // 替代原先的点击事件，检测点击 or 拖动
        setupCollapsedTextTouch()

        handler.post(updateRunnable)
    }

    private fun setupCollapsedTextTouch() {
        var initialX = 0
        var initialY = 0
        var initialTouchX = 0f
        var initialTouchY = 0f
        var downTime = 0L
        val CLICK_THRESHOLD = 200
        val MOVE_THRESHOLD = 10
        val SNAP_THRESHOLD = Resources.getSystem().displayMetrics.widthPixels / 9  // 吸附阈值

        collapsedText.setOnTouchListener { _, event ->
            // 每次触摸都重置自动收缩
            resetAutoCollapseTimer()

            when (event.action) {
                MotionEvent.ACTION_DOWN -> {
                    initialX = layoutParams.x
                    initialY = layoutParams.y
                    initialTouchX = event.rawX
                    initialTouchY = event.rawY
                    downTime = System.currentTimeMillis()
                    true
                }

                MotionEvent.ACTION_MOVE -> {
                    val dx = (event.rawX - initialTouchX).toInt()
                    val dy = (event.rawY - initialTouchY).toInt()
                    if (dx.absoluteValue > MOVE_THRESHOLD || dy.absoluteValue > MOVE_THRESHOLD) {
                        layoutParams.x = (initialX + dx).coerceIn(
                            0,
                            displayMetrics.widthPixels - rootLayout.width
                        )
                        layoutParams.y = (initialY + dy).coerceIn(
                            0,
                            displayMetrics.heightPixels - rootLayout.height
                        )
                        wm.updateViewLayout(rootLayout, layoutParams)
                    }
                    true
                }

                MotionEvent.ACTION_UP -> {

                    val upTime = System.currentTimeMillis()
                    val dx = (event.rawX - initialTouchX).toInt()
                    val dy = (event.rawY - initialTouchY).toInt()
                    val duration = upTime - downTime

                    if (duration < CLICK_THRESHOLD && dx.absoluteValue < MOVE_THRESHOLD && dy.absoluteValue < MOVE_THRESHOLD) {
                        toggleView(!isExpanded)
                    } else {
                        // 自动吸附到左右边缘
                        val screenWidth = displayMetrics.widthPixels
                        layoutParams.x = when {
                            layoutParams.x < SNAP_THRESHOLD -> 0
                            layoutParams.x > screenWidth - rootLayout.width - SNAP_THRESHOLD -> screenWidth - rootLayout.width
                            else -> layoutParams.x
                        }

                        wm.updateViewLayout(rootLayout, layoutParams)

                        prefs.edit()
                            .putInt("x", layoutParams.x)
                            .putInt("y", layoutParams.y)
                            .apply()
                    }
                    true
                }

                else -> false
            }
        }
    }

    private fun resetAutoCollapseTimer() {
        if (isExpanded) {
            autoCollapseHandler.removeCallbacks(autoCollapseRunnable)
            autoCollapseHandler.postDelayed(autoCollapseRunnable, 5000)
        }
    }

    private fun toggleView(expand: Boolean) {
        rootLayout.post {
            if (expand && !isExpanded) {
                // 展开：显示按钮并增加高度
                hideButton.visibility = View.VISIBLE
                hideButton.measure(
                    View.MeasureSpec.makeMeasureSpec(rootLayout.width, View.MeasureSpec.EXACTLY),
                    View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED)
                )

                val initialHeight = rootLayout.height
                val targetHeight = initialHeight + hideButton.measuredHeight + 40

                // 锁定rootLayout宽度，防止显示hideButton时宽度发生变化
                val currentWidth = rootLayout.width
                rootLayout.layoutParams = rootLayout.layoutParams.apply {
                    width = currentWidth // 加这一行
                }

                ValueAnimator.ofInt(initialHeight, targetHeight).apply {
                    duration = 300
                    addUpdateListener {
                        val value = it.animatedValue as Int
                        rootLayout.layoutParams = rootLayout.layoutParams.apply {
                            height = value
                        }
                        wm.updateViewLayout(rootLayout, layoutParams)
                    }
                    start()
                }

                hideButton.translationY = -hideButton.height.toFloat()
                hideButton.animate()
                    .translationY(0f)
                    .setDuration(300)
                    .start()

                isExpanded = true

                // 启动 5 秒自动收缩计时器
                autoCollapseHandler.removeCallbacks(autoCollapseRunnable)
                autoCollapseHandler.postDelayed(autoCollapseRunnable, 5000)
            } else if (!expand && isExpanded) {
                // 折叠：隐藏按钮并减小高度
                val initialHeight = rootLayout.height
                val targetHeight = initialHeight - hideButton.height - 40

                hideButton.animate()
                    .translationY(-hideButton.height.toFloat() / 2 + 40)
                    .setDuration(300)
                    .withEndAction {
                        hideButton.visibility = View.GONE
                    }
                    .start()

                ValueAnimator.ofInt(initialHeight, targetHeight).apply {
                    duration = 300
                    addUpdateListener {
                        val value = it.animatedValue as Int
                        rootLayout.layoutParams = rootLayout.layoutParams.apply {
                            height = value
                        }
                        wm.updateViewLayout(rootLayout, layoutParams)
                    }
                    start()
                }

                isExpanded = false

                // 取消自动收缩任务
                autoCollapseHandler.removeCallbacks(autoCollapseRunnable)
            }
        }
    }


    override fun onDestroy() {
        super.onDestroy()
        handler.removeCallbacks(updateRunnable)
        try {
            wm.removeView(rootLayout)
        } catch (_: Exception) {
        }
    }

    override fun onBind(intent: Intent?): IBinder? = null

    override fun onTaskRemoved(rootIntent: Intent?) {
        super.onTaskRemoved(rootIntent)
        // 移除悬浮窗
        try {
            wm.removeView(rootLayout)
        } catch (_: Exception) {
        }

        handler.removeCallbacks(updateRunnable)
        stopSelf() // 停止服务
    }
}
